package com.hxzy.shop.controller;

import com.hxzy.shop.cachedao.AuthCacheService;
import com.hxzy.shop.constant.RedisConstant;
import com.hxzy.shop.constant.ShopConstant;
import com.hxzy.shop.dto.auth.req.VcodeReq;
import com.hxzy.shop.vo.Result;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 获取RSA公钥接口
 * https://developer.aliyun.com/article/1118693  认证生成方案
 *
 * @Author wxy
 * @Date 2021/2/8 11:05
 * @Version 1.0
 */
@RestController
@Api(tags = "获取RSA公钥接口")
@RequestMapping("/rsa")
public class KeyPairController {

    @Resource
    private HttpServletResponse response;

    @Resource
    private AuthCacheService redisService;

    @Autowired
    private KeyPair keyPair;

    @GetMapping(value = "/publicKey")
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping(value = "/vCode")
    public Result< Map<String,String> > captcha(VcodeReq vcodeReq){
        //多态    工厂方法  https://blog.csdn.net/qq_25827845/article/details/52503884
        Captcha captcha=null;

        if(ShopConstant.PNG.equals( vcodeReq.getType())){
            captcha=new SpecCaptcha(vcodeReq.getWidth(), vcodeReq.getHeight());
        }else if(ShopConstant.GIF.equals(vcodeReq.getType())){
            captcha=new GifCaptcha(vcodeReq.getWidth(), vcodeReq.getHeight());
        }else{
            captcha= new ArithmeticCaptcha(vcodeReq.getWidth(),vcodeReq.getHeight());
        }
        captcha.setLen(vcodeReq.getCodeCount());
        //验证码的结果
        String value = captcha.text();
        //令牌
        String uuid= UUID.randomUUID().toString();
        //存放到redis中 "back:captcha:"+uuid
        String redisKey= RedisConstant.CAPTCHA_KEY+uuid;

        //存入到redis，10分钟过期
        this.redisService.saveVCode(redisKey, value);

        //返回给前端
        Map<String,String> map=new HashMap<>(16);
        map.put("uuid",uuid);
        map.put("image", captcha.toBase64());
        return  Result.success(map);
    }
}
